﻿using Meta.Vlc.Interop.MediaPlayer;
using NAudio.Utils;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using VideoCarousel.Control;
using VideoCarousel.Entity;
using static Microsoft.WindowsAPICodePack.Shell.PropertySystem.SystemProperties.System;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;

namespace VideoCarousel
{
    
    /// <summary>
    /// AudioWindow.xaml 的交互逻辑
    /// </summary>
    public partial class AudioWindow : Window, IPlayCtr
    {
        NAudio.Wave.WaveOut waveOut;
        AudioFileReader audioFileReader = null;
        public static List<string> GetAllName()
        {
            List<string> list = new List<string>();
            list.Add("default");
            for (int i = 0; i < WaveOut.DeviceCount; i++)
            {
                list.Add(WaveOut.GetCapabilities(i).ProductName);
            }
            return list;
        }
        public static int GetDeviceIndex(string name)
        {
            for (int i = 0; i < WaveOut.DeviceCount; i++)
            {
                if(WaveOut.GetCapabilities(i).ProductName==name)
                    return i;
            }
            return -1;
        }
        public AudioWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
            this.Closing += MainWindow_Closing;

            var index =GetDeviceIndex(VCLib.Util.ConfigHelp.ReadConfig("audioDevice"));
           
            waveOut = new NAudio.Wave.WaveOut();
            
            waveOut.DeviceNumber = index;


        }
        private bool isClose = false;
        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            isClose = true;
            waveOut?.Dispose();
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
             CarouselInit();
            //rootTemp = VCLib.Util.ConfigHelp.ReadConfig("videoFolder");


            waveOut.PlaybackStopped += WaveOut_PlaybackStopped;


            AppControl.Instance.rootPath = rootTemp;
            AppControl.Instance.PlayCtr = this;
            AppControl.Instance.Init();
            this.DataContext = AppControl.Instance;
            SetVolume(AppControl.Instance.PlayStateInfo.Vol);
            Full(AppControl.Instance.PlayStateInfo.IsFull);


           // AppControl.Instance.PlayStateInfo.PlayType = 3;
        }

        private void WaveOut_PlaybackStopped(object sender, NAudio.Wave.StoppedEventArgs e)
        {
            if (isStop)
            {
                isStop = false;
                return;
            }
            if (AppControl.Instance.PlayStateInfo.PlayType == 1)
            {
                System.Threading.Tasks.Task.Run(() => {
                    Dispatcher.Invoke(() => {
                        if (AppControl.Instance.PlayStateInfo.FullName != null)
                        {
                            if (audioFileReader != null)
                            {
                                audioFileReader.Close();
                            }
                            audioFileReader = new AudioFileReader(AppControl.Instance.PlayStateInfo.FullName);
                            waveOut.Init(audioFileReader);
                            waveOut.Play();
                        }
                    });
                });
            }
            else if (AppControl.Instance.PlayStateInfo.PlayType == 2)
            {
                System.Threading.Tasks.Task.Run(() => {
                    AppControl.Instance.NextPlay();
                });

            }
            else if (AppControl.Instance.PlayStateInfo.PlayType == 3)
            {
                System.Threading.Tasks.Task.Run(() => {
                    AppControl.Instance.RandowPlay();
                });

            }
            else
            {
                AppControl.Instance.PlayStateInfo.PlayState = 0;
            }
        }

        private string rootTemp = null;
        private void CarouselInit()
        {


            MenuItem updateFolder = new MenuItem() { Header = "更换视频文件夹" };
            updateFolder.Click += UpdateFolder_Click;
            contextMenu.Items.Insert(0, updateFolder);



            string folder = VCLib.Util.ConfigHelp.ReadConfig("videoFolder");
            
        check2:

            if (System.IO.Directory.Exists(folder))
            {
                rootTemp = folder;
            }
            else
            {
                var msgRes = MessageBox.Show("视频文件夹不存在，是否重新选择路径", "提示", MessageBoxButton.YesNo);
                if (msgRes == MessageBoxResult.Yes)
                {
                    folder = OpenFolder();
                    if (folder == null)
                    {
                        this.Close();
                        return;
                    }
                    VCLib.Util.ConfigHelp.SaveConfig("videoFolder", folder);

                    goto check2;
                }
                else
                {
                    this.Close();
                    return;
                }
            }

        }
        private void UpdateFolder_Click(object sender, RoutedEventArgs e)
        {
            string folder = OpenFolder();
            if (folder != null)
            {
                VCLib.Util.ConfigHelp.SaveConfig("videoFolder", folder);
                MessageBox.Show("保存成功，重启生效");
            }
        }
        private string OpenFolder()
        {
            Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog openFileDialog = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            openFileDialog.IsFolderPicker = true;
            openFileDialog.Multiselect = true;
            if (openFileDialog.ShowDialog() == Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult.Ok)
            {
                return openFileDialog.FileName;
            }
            return null;

        }
   

        private void Set_Click(object sender, RoutedEventArgs e)
        {
            var topmost = this.Topmost;
            if (topmost)
                this.Topmost = false;
            SetWindow.Set();
            if (topmost)
                this.Topmost = true;
        }

        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        public void Play(string fileName)
        {
            Dispatcher.Invoke(new Action(() => {
                if (!System.IO.File.Exists(fileName))
                    throw new Exception("文件不存在");
                if (audioFileReader != null)
                {
                    audioFileReader.Close();
                }
                audioFileReader = new AudioFileReader(fileName);
                waveOut.Init(audioFileReader);
                waveOut.Play();
                AppControl.Instance.PlayFileNameUpdate(fileName);
            }));
        }

        public void Play()
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                if (AppControl.Instance.PlayStateInfo.FullName != null)
                {
                    if (AppControl.Instance.PlayStateInfo.PlayState == 0)
                    {
                        Play(AppControl.Instance.PlayStateInfo.FullName);
                    }
                    else
                    {
                        AppControl.Instance.PlayStateInfo.PlayState = 1;
                        waveOut.Play();
                    }
                   
                }
            }));
        }
        bool isStop = false;
        public void Stop()
        {
            Dispatcher.Invoke(new Action(() =>
            {

                AppControl.Instance.PlayStateInfo.PlayState = 0;
                isStop = true;
                waveOut.Stop();

            }));
          
        }

        public void Pause()
        {
            Dispatcher.Invoke(new Action(() =>
            {

                waveOut.Pause();
                AppControl.Instance.PlayStateInfo.PlayState = 2;

            }));
        }

        public void Seek(double time)
        {
            if (audioFileReader != null)
            {
                if(audioFileReader.CanSeek)
                {
                    audioFileReader.Seek((long)time* audioFileReader.WaveFormat.AverageBytesPerSecond, SeekOrigin.Begin);
                }

            }
        }

        public void SetVolume(int volume)
        {
            Dispatcher.Invoke((Action)(() =>
            {
                var v = volume / 100f;
                waveOut.Volume = v;
            }));
        }

        public void Full(int isFull)
        {
            
        }

        public void UpdatePlaySate()
        {
            if (isClose) return;
            Dispatcher.Invoke((Action)(() => {
                if (audioFileReader != null)
                {
                    
                   
                    AppControl.Instance.PlayStateInfo.Current = audioFileReader.CurrentTime.TotalSeconds;
                    AppControl.Instance.PlayStateInfo.Count = audioFileReader.TotalTime.TotalSeconds;

                }
                try
                {
                    AppControl.Instance.PlayStateInfo.Vol = (int)(waveOut.Volume * 100);

                }
                catch (Exception)
               {

                }

            }));
        }
    }
}
